<?php

namespace plugin\laoha\app\admin\controller;


use plugin\laoha\app\model\Cate;
use plugin\laoha\app\validate\TitleValidate;
use support\Request;

class CateController extends CrudController
{
	protected $noNeedAuth = ['select','show','list','groups','filter_select','check'];
	protected $dataLimitField = false;
	protected $dataLimit = 'auth';
	protected $root = '';

    public function __construct()
    {
		$this->model = new Cate;
		$this->validate = new TitleValidate;
		$roots = plugin_config_merge('cate.roots');
		$root= request()->input('root', array_keys($roots)[0]);
		$this->root = $root;
    }

    public function index(Request $request)
    {   
		$roots = plugin_config_merge('cate.roots');
		$config = plugin_config_merge('app.'.$this->root);
		$navs=[];
		foreach($roots as $k=>$v){
			if($this->root == $k){
				$navs[] = ['label'=>$v,"to"=>'/app/laoha/admin/cate?root='.$k,"active"=>true];
			}else{
				$navs[] = ['label'=>$v,"to"=>'/app/laoha/admin/cate?root='.$k];
			}
		}
		$title = $roots[$this->root]??[];		
		$rules = $this->getRules();
		return view('cate/index',['params'=>['rules'=>$rules,'config'=>$config,'roots'=>$roots,'root'=>$this->root,'navs'=>$navs]]);
    }


    /**
     * 列表
     */
	public function list(Request $request)
	{
		$this->set = ['page_type'=>3,'order_by'=>'root,sort','root'=>$this->root];		
		//$count_name = $this->root.'s as count';
		//$this->model = $this->model->withCount($count_name);
		return parent::list($request);
	}

	public function groups(Request $request)
	{		
		$cate = $this->model->find($request->input('id'));

		if(!empty($cate->groups)){
			return json(str2arr($cate->groups));
		}else{
			return json([]);
		}

	}


    public function select(Request $request)
    {      
		$set = array_merge($request->all(),['page_type'=>3,'order_by'=>'sort,id']);		
		$data = laoha_query($this->model,$set);
		return json_ok($data);
    }

	public function filter_select(Request $request)
	{	
		$set = array_merge($request->all(),['page_type'=>3,'order_by'=>'sort,id']);
		$data = laoha_query($this->model,$set);
		$data = filter_cates($data);
		return json_ok($data);
	}

}
